import json

from django.http import HttpResponse, JsonResponse

from backend.models import Performance, Project, Achievement
from .util import *


def save(request):
    """
    新增 / 修改 绩效分配信息
    :param request:
    :return:
    """
    if request.method != 'POST':
        return format_response(WRONG_METHOD)

    project_id, type_id, performance_list = format_param(request, "project_id", "type", "list")

    if not project_id:
        return format_response(WRONG_POINTER)

    if not type_id:
        return format_response(WRONG_PARAM)

    for item in performance_list:
        if not item['user_id']:
            return format_response(WRONG_PARAM)
        if item['achievement'] <= 0:
            return format_response(WRONG_PARAM)

    old_data = Achievement.objects.all().filter(project_id=project_id)
    iterator = 0
    for item in old_data:
        if iterator < len(performance_list):
            item.type = type_id
            item.user_id = performance_list[iterator]['user_id']
            item.number = performance_list[iterator]['achievement']
        else:
            item.status = False
        item.save()
        print('old', item)
        iterator += 1
    if iterator < len(performance_list):
        for i in range(len(performance_list) - iterator):
            p = CetcAchievement(
                project_id=project_id,
                user_id=performance_list[iterator]['user_id'],
                type=type_id,
                number=performance_list[iterator]['achievement']
            )
            iterator += 1
            p.save()
            print('new', p)
    return format_response(SUCCESS, )


def get_by_project(request):
    """
    根据项目获取绩效信息
    :param request:
    :return:
    """
    project_id = request.GET.get('project_id')
    if not project_id:
        return format_response(WRONG_PARAM)
    p = CetcAchievement.objects.all().filter(project_id=project_id)
    data = []
    for item in p:
        data.append({
            'type': item.type,
            'nickname': item.user.get_full_name(),
            'user_id': item.user.id,
            'achievement': item.number,
            'num': item.get_true_num()
        })
    return format_response(SUCCESS, data)


def get_by_user(request):
    """
    根据成员获取绩效信息
    :param request:
    :return:
    """
    user_id = request.GET.get('user_id')
    if not user_id:
        return format_response(WRONG_PARAM)
    p = CetcPerformance.objects.all().filter(user_id=user_id)
    data = []
    for item in p:
        data.append({
            'type': item.type,
            'project_title': item.project_info(),
            'achievement': item.number,
        })
    return format_response(SUCCESS, data)
